package com.chao.common.util.log;

import com.chao.common.util.log.Inter;
import com.chao.common.util.reaction.ReactionImpl;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Order(0)
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    protected boolean isApiResult(MethodParameter returnType) {
        Inter inter = returnType.getMethodAnnotation(Inter.class);
        if(null == inter){
            return false;
        }
        return inter.answer();
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return isApiResult(returnType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return (body instanceof ReactionImpl)? body : new ReactionImpl(body);
    }

}